import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import router from 'umi/router';
import { message } from 'antd';
import { fetchValidation } from '@/utils';

import {
  queryBatchAddList,
  operBatchAdd,
} from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    operAdd: Effect;
  };
  reducers: {
    save: Reducer;
    clear: Reducer;
  };
}

const stateInfo = {
  dataInfo: [],
};

const Model: ModelType = {
  namespace: 'cooperationCompanyBatch',

  state: stateInfo,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryBatchAddList, payload);
      yield put({
        type: 'save',
        payload: response.body,
      });
    },

    * operAdd({ payload }, { call, put }) {
      const response = yield call(operBatchAdd, payload);
      const data = fetchValidation(response);
      if (data) {
        message.success('添加成功');
        yield put({
          type: 'global/setPath',
        });
        router.goBack();
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        dataInfo: action.payload,
      };
    },

    clear() {
      return stateInfo;
    },
  },
};

export default Model;
